// miniprogram/pages/navigation/navigation.js
const strutil = require('../../utils/str');
const db = require('../../utils/db');

Page({
  data: {
    input: {
      type: String,
      value: ''
    },
    result: {
      type: Array,
      value: []
    },
    busy: {
      type: Boolean,
      value: false
    },
    found: {
      type: Boolean,
      value: false
    },
    searchInitiated: {
      type: Boolean,
      value: false
    }
  },

  onLoad: function (options) {

  },

  onReady: function () {
    this.getTabBar().update();
    this.setData({
      input: '',
      busy: false,
      found: false,
      searchInitiated: false
    });
  },

  onScanTap: function () {
    wx.scanCode({
      success: (res) => {
        const code = res.result;
        if (code != null) {
          if (strutil.isNumber(code)) {
            wx.navigateTo({
              url: '../book_details/book_details?mode=isbn&input=' + code,
            })
          } else {
            wx.showToast({
              title: '仅支持扫描图书条形码',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  doSearch: function (e) {
    const input = e.detail.value.trim();
    if (strutil.isNumber(input) && (input.length == 10 || input.length == 13)) {
      // isbn
      wx.navigateTo({
        url: '../book_details/book_details?mode=isbn&input=' + input,
      })
    } else {
      this.setData({
        busy: true,
        searchInitiated: true
      });
      db.queryBooks(input).then(res => {
        if (res.code === 0) {
          console.log(res.result.data);
          if (res.result.data.length > 0) {
            this.setData({
              busy: false,
              found: true,
              result: res.result.data
            });
          } else {
            this.setData({
              busy: false,
              found: false
            });
          }
        } else {
          wx.showToast({
            title: '服务器异常',
          });
        }
      });
    }
  }
})
